<template>
  <div id="sql">
    <div class="sql-main">
      <!-- 选择区 -->
      <el-card class="selection-area">
        <el-form :inline="true" :model="form" class="demo-form-inline">
          <el-form-item label="数据库类型">
            <el-select v-model="form.dataType" placeholder="请选择数据库类型" clearable @change="dataTypeChange">
              <el-option
                v-for="item in dataTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="系统名称">
            <el-select v-model="form.name" placeholder="请选择系统名称" clearable @change="nameChange" :disabled="nameDisabled">
              <el-option
                v-for="item in nameOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="数据库名">
            <el-select v-model="form.dataName" placeholder="请选择数据库名" clearable :disabled="dataNameDisabled">
              <el-option
                v-for="item in dataNameOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <div class="run" @click="executeSql">
              <svg-icon icon-class="run" />
              <span>{{ runText }}</span>
            </div>
          </el-form-item>
        </el-form>
      </el-card>
      <!-- sql输入区 -->
      <el-card class="sql-input">
        <el-input type="textarea" v-model="sql" @select.native="selectSql" @mouseup.native="mouseupSql" @blur="blurSql"></el-input>
      </el-card>
      <!-- 查询结果 -->{{ errorMsg }}
      <el-tabs type="border-card" v-show="result.length != 0 || errorMsg != null">
        <el-tab-pane label="错误信息" v-if="errorMsg != null" class="errTab">
          <div>{{ errorMsg }}</div>
        </el-tab-pane>
        <el-tab-pane :label="result.length == 1 ? '结果' : '结果' + (index + 1)" v-for="(item, index) in result" :key="index">
          <!-- 循环获取表数据 -->
          <el-table :data="item.valList" height="260" border style="width: 100%;">
            <!-- 循环获取表头 -->
            <el-table-column :prop="title" :label="title" width="180" v-for="(title, i) in item.nameList" :key="i">
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>
    <div class="sql-tree">
      <el-card>
        <el-tree :data="treeList" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
      </el-card>
    </div>
  </div>
</template>

<script>
  import common from '@/api/common'
  import connect from '@/api/connect'
  import sql from '@/api/sql'
  export default {
    name: 'SQL',
    data() {
      return {
        form: {
          dataType: null,
          name: null,
          dataName: null
        },
        // 数据库类型下拉选择器
        dataTypeOptions: [],
        // 系统名称下拉选择器
        nameOptions: [],
        // 数据库名称下拉选择器
        dataNameOptions: [],
        // 系统名称下类选择器是否禁用
        nameDisabled: true,
        // 数据库名称下拉选择器是否禁用
        dataNameDisabled: true,
        // sql语句
        sql: null,
        // 选中的sql
        currentSql: null,
        isSelect: false,
        result: [],
        errorMsg: null,
        // textareaValue: '<textarea autocomplete="off" class="el-textarea__inner" style="min-height: 32.6px;"></textarea>'
        treeList:  [{
          label: '一级 1',
          children: [{
            label: '二级 1-1',
            children: [{
              label: '三级 1-1-1'
            }]
          }]
        }, {
          label: '一级 2',
          children: [{
            label: '二级 2-1',
            children: [{
              label: '三级 2-1-1'
            }]
          }, {
            label: '二级 2-2',
            children: [{
              label: '三级 2-2-1'
            }]
          }]
        }, {
          label: '一级 3',
          children: [{
            label: '二级 3-1',
            children: [{
              label: '三级 3-1-1'
            }]
          }, {
            label: '二级 3-2',
            children: [{
              label: '三级 3-2-1'
            }]
          }]
        }],
        defaultProps: {
          children: 'children',
          label: 'label'
        }
      }
    },
    // 计算属性
    computed: {
      runText() {
        return this.currentSql == '' || this.currentSql == null ? '运行' : '运行已选择的';
      }
    },
    // 监听器，监听下拉列表
    watch: {
      'form.dataType'(newVal, oldVal) {
        console.log(newVal, oldVal)
        if (newVal) {
          this.nameDisabled = false
        } else {
          this.nameDisabled = true
          this.form.name = null
        }
      },
      'form.name'(newVal, oldVal) {
        if (newVal) {
          this.dataNameDisabled = false
        } else {
          this.dataNameDisabled = true
          this.form.dataName = null
        }
      }
    },
    methods: {
      // 根据数据库类型查询系统名称
      getNameByDataType() {
        if (!this.form.dataType) {
          return;
        }
        connect.getNameByDataType(this.form.dataType).then(res => {
          // 先将原来的数组清空
          this.nameOptions = []
          res.data.map(item => {
            this.nameOptions.push({
              value: item,
              label: item
            })
          })
        })
      },
      // 根据数据库类型和系统名称查询数据库名
      getDataNameByDataTypeAndName() {
        if (!this.form.name) {
          return;
        }
        connect.getDataNameByDataTypeAndName(this.form.dataType, this.form.name).then(res => {
          // 先将原来的数组清空
          this.dataNameOptions = []
          res.data.map(item => {
            this.dataNameOptions.push({
              value: item,
              label: item
            })
          })
        })
      },
      // 数据库类型下拉选择器选中事件
      dataTypeChange() {
        this.getNameByDataType()
      },
      // 系统名称下拉选择器选中事件
      nameChange() {
        this.getDataNameByDataTypeAndName()
      },
      // 执行sql语句
      executeSql() {
        // 执行前现将错误信息清空
        this.errorMsg = null
        // 要传递给后端的参数
        let param;
        // 如果没有选择，就执行所有的；如果选择了，就执行选择的
        if (!this.currentSql) {
          param = this.sql
        } else {
          param = this.currentSql
        }
        sql.executeSql(param).then(res => {
          if (res.code != 200) {
            this.errorMsg = res.msg
          }
          this.result = res.data
        })
      },
      // 选中sql，调用input的原生时间，@click需要用native修饰
      selectSql(e) {
        // // 获取选中字符串的起始下标、结束下标与输入框的值
        // let start = e.target.selectionStart
        // let end = e.target.selectionEnd
        // let val = e.target.value
        // let selectVal = ''
        // // 防止没有选中
        // if (val && end != 0) {
        //   selectVal = val.slice(start, end)
        // }

        // const highlightedText = `<mark>${selectVal}</mark>`; // 使用 <mark> 标签包裹选中的文本
        // const newText = val.slice(0, start) + highlightedText + val.slice(end);
        // this.textareaValue = `<textarea autocomplete="off" class="el-textarea__inner" style="min-height: 32.6px;">${newText}</textarea>`

        let selectedText = '';
        if (window.getSelection().toString().length > 0) {
          selectedText = window.getSelection().toString();
        } else {
          selectedText = '';
        }
        this.currentSql = selectedText
      },
      // 鼠标点击取消选择
      mouseupSql() {
        if (this.currentSql) {
          this.currentSql = null
        }
      },
      // 文本域失去焦点取消选择
      blurSql() {
        // 定时器，避免失去焦点时直接清空选中sql，这样当选中sql后点击运行按钮是有效果的
        if (this.currentSql) {
          setTimeout(() => {
            this.currentSql = null
          }, 500);
        }
      },
      handleNodeClick(data) {
        console.log(data);
      }
    },
    directives: {
      highlight: {
        bind(el) {
          el.addEventListener('mouseup', () => {
            const selection = window.getSelection().toString();
            if (selection) {
              const span = document.createElement('span');
              span.style.backgroundColor = 'yellow';
              const range = window.getSelection().getRangeAt(0);
              range.surroundContents(span);
            }
          });
        },
      },
    },
    mounted() {
      // 加载数据库类型选择器数据
      common.getDataType().then(res => {
        this.dataTypeOptions = res.data;
      })
    },
  }
</script>

<style lang="scss" scoped>
  #sql {
    position: relative;
    height: 100%;
    display: flex;
    // 查询区域
    .sql-main {
      flex: 1;
      min-width: 1096px;
      .el-tabs {
        width: 100%;
        height: 300px;
        position: absolute;
        // position: relative;
        bottom: 0;
        .errTab {
          display: flex;
          justify-content: center; 
          align-items: center;
          height: 260px;
        }
      }
    }
    // 右侧树结构区域
    .sql-tree {
      width: 200px;
      min-width: 200px;
      margin-left: 10px;
      .el-card {
        height: 100%;
      }
    }
  }
  .selection-area.el-card {
    .el-form-item {
      margin: 0 30px 0 0;
      .run {
        display: flex;
        align-items: center;
        cursor: pointer;
        &:hover {
          background: rgba(216,230,242, 0.8);
        }
        .svg-icon {
          width: 30px;
          height: 30px;
        }
      }
    }
  }
  
</style>

<style scoped>
  .selection-area >>> .el-input__inner {
    width: 160px;
  }
  .sql-input >>> .el-textarea__inner {
    height: 350px;
  }
  >>> .el-tabs--border-card>.el-tabs__content {
    padding: 0;
  }
</style>